/*
 * FormManager.cpp
 *
 *  Created on: 2011. 4. 14.
 *      Author: JeeHoon
 */

#include <stdlib.h>
#include <FApp.h>
#include "FormManager.h"
#include "Common.h"


FormManager::FormManager()
{
	__pForms = NULL;
	__nFormsTop = -1;
}

FormManager::~FormManager()
{
	free(__pForms);
}

result
FormManager::SetStartForm(Osp::Ui::Controls::Form * pMainFrom)
{
	result r = E_SUCCESS;

	__nFormsTop++;
	void * tmp = realloc(__pForms,__nFormsTop+1*sizeof(void*));
	if(NULL == tmp) r = E_OUT_OF_MEMORY;
	if(E_SUCCESS == r)
	{
		__pForms = (Osp::Ui::Controls::Form **)tmp;
		__pForms[__nFormsTop] = pMainFrom;
	}

	return r;
}

result
FormManager::PushForm(Osp::Ui::Controls::Form * pForm)
{
	Osp::Ui::Controls::Frame *pFrame = Osp::App::Application::GetInstance()->GetAppFrame()->GetFrame();

	result r = E_SUCCESS;

	Osp::Ui::Controls::Form * pCurrentFrom = getCurrentForm();
	pCurrentFrom->SetEnabled(false);
	pCurrentFrom->SetShowState(false);

	__nFormsTop++;
	void * tmp = realloc(__pForms,__nFormsTop+1*sizeof(void*));
	if(NULL == tmp) r = E_OUT_OF_MEMORY;
	if(E_SUCCESS == r)
	{
		__pForms = (Osp::Ui::Controls::Form **)tmp;
		__pForms[__nFormsTop] = pForm;
	}

	if(E_SUCCESS == r) r = pForm->Construct(Osp::Ui::Controls::FORM_STYLE_NORMAL);
	if(E_SUCCESS == r) r = pFrame->AddControl(*pForm);
	if(E_SUCCESS == r) r = pFrame->SetCurrentForm(*pForm);
	if(E_SUCCESS == r) r = pForm->Draw();
	if(E_SUCCESS == r) r = pForm->Show();

	return r;
}

result
FormManager::PopForm()
{
	Osp::Ui::Controls::Frame *pFrame = Osp::App::Application::GetInstance()->GetAppFrame()->GetFrame();

	result r = E_SUCCESS;

	if(__nFormsTop == 0)
	{
		return E_FAILURE;
	}

	Osp::Ui::Controls::Form * pCurrentFrom = getCurrentForm();
	pFrame->RemoveControl(*pCurrentFrom);

	__nFormsTop--;
	void * tmp = realloc(__pForms,__nFormsTop+1*sizeof(void*));
	if(NULL == tmp) r = E_OUT_OF_MEMORY;
	if(E_SUCCESS == r)
		__pForms = (Osp::Ui::Controls::Form **)tmp;

	pCurrentFrom = getCurrentForm();

	if(E_SUCCESS == r) r = pFrame->SetCurrentForm(*pCurrentFrom);
	if(E_SUCCESS == r) r = pCurrentFrom->Draw();
	if(E_SUCCESS == r) r = pCurrentFrom->Show();

	return r;
}


Osp::Ui::Controls::Form *
FormManager::getCurrentForm()
{
	return __pForms[__nFormsTop];
}

